package com.xoa.dev.pz.service.impl;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.party.GridInfoMapper;
import com.xoa.dev.pz.dao.MenuJdtMapper;
import com.xoa.dev.pz.dao.PzCorrectionMapper;
import com.xoa.dev.pz.dao.PzPersonMapper;
import com.xoa.model.common.SysCode;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.party.GridInfo;
import com.xoa.dev.pz.model.PzCorrection;
import com.xoa.dev.pz.model.PzCorrectionWithBLOBs;
import com.xoa.dev.pz.model.PzPersonExample;
import com.xoa.dev.pz.model.PzPersonWithBLOBs;
import com.xoa.model.users.Users;
import com.xoa.service.sys.SysLogService;
import com.xoa.service.users.UsersService;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.GetAttachmentListUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.L;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.netdisk.CheckAll;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by 李显 on 2017/12/2.
 * 社区矫正
 */
@Service
public class PzCorrectionService {

    @Resource
    private PzCorrectionMapper pzCorrectionMapper;

    @Resource
    private PzPersonMapper pzPersonMapper;

    @Resource
    private UsersService usersService;
    @Resource
    private SysLogService sysLogService;
    @Resource
    private SysCodeMapper sysCodeMapper;

    @Resource
    private GridInfoMapper gridInfoMapper;

    @Resource
    private MenuJdtMapper menuJdtMapper;
    /**
     * 创建人：李显
     * 创建时间：2017年12月2日 13:00:08
     * 方法介绍：添加
     * 参数说明：
     */
    public ToJson<PzCorrectionWithBLOBs> insertSelective(HttpServletRequest request, PzCorrectionWithBLOBs record){
        ToJson<PzCorrectionWithBLOBs> json = new ToJson<>();
        try{
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            record.setCreateUser(users.getUserId());
            record.setCreateTime(DateFormat.getDatestr(new Date()));
            if(record.getFourHistoryFlag()==null){
                record.setFourHistoryFlag("0");
            }
            if(record.getThreeStakeholdersFlag()==null){
                record.setThreeStakeholdersFlag("0");
            }
            if(record.getRepeatOffendersFlag()==null){
                record.setRepeatOffendersFlag("0");
            }
            pzCorrectionMapper.insertSelective(record);
            sysLogService.setPzLog(request,users.getUserId(),new Date(),"1","2","社区矫正人员");
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

    public ToJson<PzCorrectionWithBLOBs> updateByPrimaryKeySelective (HttpServletRequest request, PzCorrectionWithBLOBs record){
        ToJson<PzCorrectionWithBLOBs> json = new ToJson<PzCorrectionWithBLOBs>(1,"error");
        try {
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            if(record.getFourHistoryFlag()==null){
                record.setFourHistoryFlag("0");
            }
            if(record.getThreeStakeholdersFlag()==null){
                record.setThreeStakeholdersFlag("0");
            }
            if(record.getRepeatOffendersFlag()==null){
                record.setRepeatOffendersFlag("0");
            }
            int count = pzCorrectionMapper.updateByPrimaryKeySelective(record);
            sysLogService.setPzLog(request,users.getUserId(),new Date(),"3","2","社区矫正人员");
            if(count > 0){
                json.setFlag(0);
                json.setMsg("ok");
                return json;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }

    public ToJson<PzCorrectionWithBLOBs> deleteByPrimaryKey(HttpServletRequest request, int correctionId){
        ToJson<PzCorrectionWithBLOBs> json = new ToJson<>();
        try {
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            pzCorrectionMapper.deleteByPrimaryKey(correctionId);
            sysLogService.setPzLog(request,users.getUserId(),new Date(),"2","2","社区矫正人员");
            json.setFlag(0);
            json.setMsg("ok");

        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }


    public ToJson<PzCorrectionWithBLOBs> queryPzCorrection(PzCorrectionWithBLOBs pzCorrectionWithBLOBs, Integer page, Integer pageSize, boolean useFlag, String output, HttpServletRequest request, HttpServletResponse response){
        ToJson<PzCorrectionWithBLOBs> json = new ToJson<PzCorrectionWithBLOBs>();

        PageParams pageParams=new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", pageParams);

        try{
            Map<String, Object> param = new HashMap<String, Object>();
            Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            param.put("userId", user.getUserId());
            param.put("userPriv", user.getUserPriv());
            param.put("deptId", user.getDeptId());
            String menuModel=menuJdtMapper.selMenuByModel("4");
            if(!CheckAll.checkAll(menuModel,param)){
                pzCorrectionWithBLOBs.setCreateUser(user.getUserId());
            }
            map.put("pzCorrection",pzCorrectionWithBLOBs);
            List<PzCorrectionWithBLOBs> list=pzCorrectionMapper.queryPzCorrection(map);
            for(PzCorrectionWithBLOBs User:list){
                if(User.getUserId()!=null){
                    PzPersonExample pzPersonExample=new PzPersonExample();
                    pzPersonExample.createCriteria().andPIdEqualTo(Integer.valueOf(User.getUserId()));
                    List<PzPersonWithBLOBs> pzPeople = pzPersonMapper.selectByExampleWithBLOBs(pzPersonExample);
                    if(pzPeople.size()>0){
                        User.setPzPerson(pzPeople.get(0));
                    }
                }
            }
            for(PzCorrectionWithBLOBs ps:list){
                if(!StringUtils.checkNull(ps.getGridUserIds())){
                    ps.setGridUserNames(usersService.getUserNameById(ps.getGridUserIds()));}

            }
            json.setTotleNum(pzCorrectionMapper.selCorrectionByCond(map));
            if(output == null){
                output="0";
            }
            if(output.equals("1")) {//output==1,则进行导出操作
                HSSFWorkbook tableWork = ExcelUtil.makeExcelHead("特殊人员-社区矫正表", 17);
                String[] secondTitles = {"社区服刑人员编号", "接受方式","关注程度","原羁押场所","犯罪类型","具体罪名","是否有四史","是否三涉","是否累惯犯","服刑类别","原判刑期","原判刑期开始时间","原判刑期结束时间","服刑开始时间","服刑结束时间","近况描述"};
                HSSFWorkbook excelWork = ExcelUtil.makeSecondHead(tableWork, secondTitles);
                String[] beanProperty = {"correctionId","acceptWay","attentionLevel","detentionOriginalPlace","crimeTypes","specificCharges","fourHistoryFlag","threeStakeholdersFlag","repeatOffendersFlag","sentenceCategory","originalSentence","originalSentenceBeginTime","originalSentenceEndTime","sentenceBeginTime","sentenceEndTime","recentDescription"};
                HSSFWorkbook workbook = ExcelUtil.exportExcelData(excelWork, list, beanProperty);
                response.setContentType("text/html;charset=UTF-8");
                OutputStream out = response.getOutputStream();

                String filename = "特殊人员-社区矫正表.xls"; //考虑多语言
                filename = FileUtils.encodeDownloadFilename(filename,
                        request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition",
                        "attachment;filename=" + filename);
                workbook.write(out);
                out.flush();
                out.close();
            }
            json.setObj(list);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;

    }

    public ToJson<PzCorrectionWithBLOBs> queryAll(PzCorrection pzCorrection, Integer page, Integer pageSize, boolean useFlag, HttpServletRequest request, HttpServletResponse response, String export, String pCradId, String pName){
        ToJson<PzCorrectionWithBLOBs> json = new ToJson<PzCorrectionWithBLOBs>();

        PageParams pageParams=new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", pageParams);
        map.put("pCradId", pCradId);
        map.put("pName", pName);
        Map<String, Object> param = new HashMap<String, Object>();
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        param.put("userId", user.getUserId());
        param.put("userPriv", user.getUserPriv());
        param.put("deptId", user.getDeptId());
        String menuModel=menuJdtMapper.selMenuByModel("4");
        if(!CheckAll.checkAll(menuModel,param)){
            pzCorrection.setCreateUser(user.getUserId());
        }
        map.put("pzCorrection",pzCorrection);
        try{
            if(export==null){
                export="0";
            }
            List<PzCorrectionWithBLOBs> list=pzCorrectionMapper.selectAll(map);
            for(PzCorrectionWithBLOBs pzCorrection1 : list){
                SysCode sysCode = sysCodeMapper.getSingleCode("RENT_CONCERN", pzCorrection1.getAttentionLevel());
                if(sysCode!=null){
                    pzCorrection1.setAttentionLevel(sysCode.getCodeName());
                }
                SysCode sysCode1 = sysCodeMapper.getSingleCode("P_CRIME_TYPE", pzCorrection1.getCrimeTypes());
                if(sysCode1!=null){
                    pzCorrection1.setCrimeTypes(sysCode1.getCodeName());
                }
                SysCode sysCode2 = sysCodeMapper.getSingleCode("ACCEPT_WAY", pzCorrection1.getAcceptWay());
                if(sysCode2!=null){
                    pzCorrection1.setAcceptWay(sysCode2.getCodeName());
                }
                SysCode sysCode3 = sysCodeMapper.getSingleCode("SENTENCE_CATEGORY", pzCorrection1.getSentenceCategory());
                if(sysCode3!=null){
                    pzCorrection1.setSentenceCategory(sysCode3.getCodeName());
                }
                //pzCorrection1.getPzPerson().setpSex(pzCorrection1.getPzPerson().getpSex()=="0"?"男":"女");
//                pzCorrection1.setpSex("0".equals(pzCorrection1.getpSex())?"女":"男");
                pzCorrection1.setpSex("0".equals(pzCorrection1.getpSex())?"男":"女");
                SysCode sysCode4 = sysCodeMapper.getSingleCode("POLITICAL", pzCorrection1.getpPolitical());
                if (sysCode4 != null) {
                    pzCorrection1.setpPolitical(sysCode.getCodeName());
                }
                SysCode sysCode5 = sysCodeMapper.getSingleCode("DEGREE", pzCorrection1.getpEducation());
                if (sysCode5 != null) {
                    pzCorrection1.setpEducation(sysCode1.getCodeName());
                }
                if ("01".equals(pzCorrection1.getpMaritalStatus())) {
                    pzCorrection1.setpMaritalStatus("未婚");
                } else {
                    pzCorrection1.setpMaritalStatus("已婚");
                }
                if ("0".equals(pzCorrection1.getpVehicles())) {
                    pzCorrection1.setpVehicles("无");
                } else {
                    pzCorrection1.setpVehicles("有");
                }
                if ("0".equals(pzCorrection1.getFourHistoryFlag())) {
                    pzCorrection1.setFourHistoryFlag("无");
                } else {
                    pzCorrection1.setFourHistoryFlag("有");
                }
                if ("0".equals(pzCorrection1.getThreeStakeholdersFlag())) {
                    pzCorrection1.setThreeStakeholdersFlag("无");
                } else {
                    pzCorrection1.setThreeStakeholdersFlag("有");
                }
                if ("0".equals(pzCorrection1.getRepeatOffendersFlag())) {
                    pzCorrection1.setRepeatOffendersFlag("无");
                } else {
                    pzCorrection1.setRepeatOffendersFlag("有");
                }




            }
            json.setTotleNum(pageParams.getTotal());
            json.setObj(list);
            json.setFlag(0);
            json.setMsg("ok");
            if(export.equals("1")){
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("社区矫正人员信息导出", 36);
                String[] secondTitles = { "姓名","性别","身份证", "曾用名/别名", "出生日期","民族","联系方式","政治面貌","文化程度","婚姻状况","宗教信仰","职业","工作单位","户籍地址","籍贯","户籍地详址","现居地址","名下机动车辆","备注","接受方式","关注程度","原羁押场所","犯罪类型","具体罪名","是否有四史","是否有三涉","是否累惯犯","服刑类别","原判刑期","原判刑期开始时间","原判刑期结束时间","服刑开始时间","服刑结束时间","近况描述"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = {"pName","pSex","pCradId", "pAlias","pDate","pNation","pPhone","pPolitical","pEducation","pMaritalStatus","pReligion","pOccupation","pWorkUnit","pDomicile","pOrigin","pDetailedDomicile","pAddress","pVehicles","pRemark", "acceptWay", "attentionLevel","detentionOriginalPlace","crimeTypes","specificCharges","fourHistoryFlag","threeStakeholdersFlag","repeatOffendersFlag","sentenceCategory","originalSentence","originalSentenceBeginTime","originalSentenceEndTime","sentenceBeginTime","sentenceEndTime","recentDescription"};
                HSSFWorkbook workbook = null;
                workbook = ExcelUtil.exportExcelData(workbook2, list, beanProperty);
                OutputStream out = response.getOutputStream();
                String filename = "社区矫正人员信息记录表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;

    }

    public ToJson<PzCorrectionWithBLOBs> selectById(int correctionId, HttpServletRequest request){
        ToJson<PzCorrectionWithBLOBs> json = new ToJson<>();
        try {
            PzCorrectionWithBLOBs pzCorrections = pzCorrectionMapper.selectById(correctionId);
            SysCode sysCode = sysCodeMapper.getSingleCode("RENT_CONCERN", pzCorrections.getAttentionLevel());
            if(sysCode!=null){
                pzCorrections.setAttentionLevelStr(sysCode.getCodeName());
            }
            SysCode sysCode1 = sysCodeMapper.getSingleCode("P_CRIME_TYPE", pzCorrections.getCrimeTypes());
            if(sysCode1!=null){
                pzCorrections.setCrimeTypesStr(sysCode1.getCodeName());
            }
            SysCode sysCode2 = sysCodeMapper.getSingleCode("ACCEPT_WAY", pzCorrections.getAcceptWay());
            if(sysCode2!=null){
                pzCorrections.setAcceptWayStr(sysCode2.getCodeName());
            }
            SysCode sysCode3 = sysCodeMapper.getSingleCode("SENTENCE_CATEGORY", pzCorrections.getSentenceCategory());
            if(sysCode3!=null){
                pzCorrections.setSentenceCategoryStr(sysCode3.getCodeName());
            }

            //附件处理
            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if(pzCorrections.getAttachmentName()!=null&&!"".equals(pzCorrections.getAttachmentName())){
                attachmentList= GetAttachmentListUtil.returnAttachment(pzCorrections.getAttachmentName(),pzCorrections.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"), GetAttachmentListUtil.MODULE_PZ_CORRECTION);
            }
            pzCorrections.setAttachmentList(attachmentList);
           /* PzCorrectionExample pzCorrectionExample=new PzCorrectionExample();
            pzCorrectionExample.createCriteria().andCorrectionIdEqualTo(correctionId);
            List<PzCorrectionWithBLOBs> pzCorrections = pzCorrectionMapper.selectByExampleWithBLOBs(pzCorrectionExample);
            if(pzCorrections.get(0)==null&&pzCorrections.size()<0){
                throw new Exception();
            }
            PzPersonExample pzPersonExample=new PzPersonExample();
            pzPersonExample.createCriteria().andPIdEqualTo(Integer.parseInt(pzCorrections.get(0).getUserId()));
            List<PzPersonWithBLOBs> pzPeople = pzPersonMapper.selectByExampleWithBLOBs(pzPersonExample);
            if(pzPeople.size()>0) {
                pzCorrections.get(0).setPzPerson(pzPeople.get(0));
            }*/
            json.setObject(pzCorrections);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

    /**
     * 创建作者:   李显
     * 创建日期:   2017年12月5日 14:48:17
     * 方法介绍:   特殊人群-社区矫正导入
     * 返回值说明:
     */
    @Transactional
    public ToJson<PzCorrectionWithBLOBs> inputFixAsserts(HttpServletRequest request, HttpServletResponse response, MultipartFile file, HttpSession session) {
        ToJson<PzCorrectionWithBLOBs> json = new ToJson<PzCorrectionWithBLOBs>(1, "error");
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            //String name = rb.getString("mysql.driverClassName");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            if (file.isEmpty()&&file==null) {
                json.setMsg("请上传文件！");
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString();
                    uuid = uuid.replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    /*file.transferTo(dest);*/
                    //将文件上传成功后进行读取文件
                    //进行读取的路径
                    //String readPath = path.append(newFileName).toString();
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();
                    InputStream in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row rowObj = null;
                    int lastRowNum = sheetObj.getLastRowNum();
                    int inputFail=0;
                    int inputSuccess=0;
                    String faillReason="";
                    for (int i = 2; i <= lastRowNum; i++) {
                        rowObj = sheetObj.getRow(i);
                        if (rowObj != null) {
                            Cell c0 = rowObj.getCell(0);
                            Cell c1 = rowObj.getCell(1);
                            Cell c2 = rowObj.getCell(2);
                            Cell c3 = rowObj.getCell(3);
                            Cell c4 = rowObj.getCell(4);
                            Cell c5 = rowObj.getCell(5);
                            Cell c6 = rowObj.getCell(6);
                            Cell c7 = rowObj.getCell(7);
                            Cell c8 = rowObj.getCell(8);
                            Cell c9 = rowObj.getCell(9);
                            Cell c10 = rowObj.getCell(10);
                            Cell c11 = rowObj.getCell(11);
                            Cell c12 = rowObj.getCell(12);
                            Cell c13 = rowObj.getCell(13);
                            Cell c14 = rowObj.getCell(14);
                            Cell c15 = rowObj.getCell(15);
                            if(c0.getStringCellValue()!=""&&c1.getStringCellValue()!=""&&c2.getStringCellValue()!=""){
                                PzCorrectionWithBLOBs pzCorrectionWithBLOBs = new PzCorrectionWithBLOBs();
                                if(!StringUtils.checkNull(c0.getStringCellValue())){
                                    pzCorrectionWithBLOBs.setCorrectionId(Integer.valueOf(c0.getStringCellValue()));
                                }
                                pzCorrectionWithBLOBs.setAcceptWay(c1.getStringCellValue());
                                pzCorrectionWithBLOBs.setAttentionLevel(c2.getStringCellValue());
                                pzCorrectionWithBLOBs.setDetentionOriginalPlace(c3.getStringCellValue());
                                pzCorrectionWithBLOBs.setCrimeTypes(c4.getStringCellValue());
                                pzCorrectionWithBLOBs.setSpecificCharges(c5.getStringCellValue());
                                pzCorrectionWithBLOBs.setFourHistoryFlag(c6.getStringCellValue());
                                pzCorrectionWithBLOBs.setThreeStakeholdersFlag(c7.getStringCellValue());
                                pzCorrectionWithBLOBs.setRepeatOffendersFlag(c8.getStringCellValue());
                                pzCorrectionWithBLOBs.setSentenceCategory(c9.getStringCellValue());
                                pzCorrectionWithBLOBs.setOriginalSentence(c10.getStringCellValue());
                                if(!StringUtils.checkNull(c10.getStringCellValue())){
                                    pzCorrectionWithBLOBs.setOriginalSentenceBeginTime(DateFormat.DateToStr(c11.getStringCellValue()));
                                }
                                if(!StringUtils.checkNull(c11.getStringCellValue())){
                                    pzCorrectionWithBLOBs.setOriginalSentenceEndTime(DateFormat.DateToStr(c12.getStringCellValue()));
                                }
                                if(!StringUtils.checkNull(c11.getStringCellValue())){
                                    pzCorrectionWithBLOBs.setSentenceBeginTime(DateFormat.DateToStr(c13.getStringCellValue()));
                                }
                                if(!StringUtils.checkNull(c11.getStringCellValue())){
                                    pzCorrectionWithBLOBs.setSentenceEndTime(DateFormat.DateToStr(c14.getStringCellValue()));
                                }
                                pzCorrectionWithBLOBs.setRecentDescription(c15.getStringCellValue());
                                if(pzCorrectionMapper.selectByPrimaryKey(Integer.parseInt(c0.getStringCellValue()))!=null){
                                    pzCorrectionMapper.insert(pzCorrectionWithBLOBs);
                                    inputSuccess++;
                                }else {
                                    inputFail++;
                                    faillReason+=c0.getStringCellValue()+",";
                                    continue;
                                }
                            }
                        }
                    }
                    PzCorrectionWithBLOBs temp=new PzCorrectionWithBLOBs();
                    temp.setInputFail(inputFail);
                    temp.setInputSuccess(inputSuccess);
                    temp.setInputFailReason(faillReason);
                    json.setFlag(0);
                    json.setMsg("ok");
                    dest.delete();
                } else {
                    json.setMsg("0");//文件类型不正确
                    return json;
                }
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("EduFixAssetsService inputFixAsserts:"+e);
            e.printStackTrace();
        }
        return json;
    }

    public ToJson<PzCorrectionWithBLOBs> importCorrection(HttpServletRequest request, HttpServletResponse response, MultipartFile file, HttpSession session) {
        ToJson<PzCorrectionWithBLOBs> toJson = new ToJson<PzCorrectionWithBLOBs>(1, "error");
        Users users= SessionUtils.getSessionInfo(request.getSession(),Users.class,new Users());
        // 成功次数
        Integer successCount = 0;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            // 判断是否为空文件
            if (file.isEmpty()) {
                toJson.setMsg("请上传文件！");
                toJson.setFlag(1);
                return toJson;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                  //  String readPath = path.append(newFileName).toString();
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();
                    InputStream in = new FileInputStream(readPath);
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    List<PzCorrectionWithBLOBs> saveList = new ArrayList<PzCorrectionWithBLOBs>();
                    List<PzPersonWithBLOBs> saveList1 = new ArrayList<PzPersonWithBLOBs>();
                    PzCorrectionWithBLOBs pzCorrectionWithBLOBs = null;
                    PzPersonWithBLOBs pzPersonWithBLOBs = null;
                    int count = 0;
                    for (int i = 1; i < lastRowNum; i++) {
                        pzCorrectionWithBLOBs = new PzCorrectionWithBLOBs();
                        pzPersonWithBLOBs = new PzPersonWithBLOBs();
                        row = sheetObj.getRow(i);
                        String value = "";
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //所属网格
                                            String as=cell.getStringCellValue();
                                            GridInfo info=gridInfoMapper.selectByUGridName(as);
                                            pzPersonWithBLOBs.setpGrid(info.getGridId());
                                            pzCorrectionWithBLOBs.setGridId(info.getGridId());
                                            break;
                                        case 1:
                                            // 姓名
                                            pzPersonWithBLOBs.setpName(cell.getStringCellValue());
                                            break;
                                        case 2:
                                            // 身份证
                                            pzPersonWithBLOBs.setpCradId(cell.getStringCellValue());
                                            break;
                                        case 3:
                                            // 别名
                                            pzPersonWithBLOBs.setpAlias(cell.getStringCellValue());
                                            break;
                                        case 4:
                                            // 性别
                                            if(cell.getStringCellValue().equals("女")){
                                                pzPersonWithBLOBs.setpSex("1");
                                            }else if(cell.getStringCellValue().equals("男")){
                                                pzPersonWithBLOBs.setpSex("0");
                                            }
                                            break;
                                        case 5:
                                            // 出生日期
                                            Date date=cell.getDateCellValue();
                                            pzPersonWithBLOBs.setpDate(date);
                                            break;
                                        case 6:
                                            // 民族
                                            pzPersonWithBLOBs.setpNation(cell.getStringCellValue());
                                            break;
                                        case 7:
                                            // 联系方式
                                            if (cell.getCellType() == CellType.NUMERIC) {
                                                BigDecimal bigP=new BigDecimal(cell.getNumericCellValue());
                                                value = bigP.toString();
                                                //解决1234.0  去掉后面的.0
                                                if(null!=value&&!"".equals(value.trim())){
                                                    String[] item = value.split("[.]");
                                                    if(1<item.length&&"0".equals(item[1])){
                                                        value=item[0];
                                                    }
                                                }
                                                pzPersonWithBLOBs.setpPhone(value);
                                            }else {
                                                pzPersonWithBLOBs.setpPhone(cell.getStringCellValue());
                                            }
                                            break;
                                        case 8:
                                            // 政治面貌
                                            pzPersonWithBLOBs.setpPolitical((sysCodeMapper.getByName("POLITICAL",cell.getStringCellValue().trim())).getCodeNo());
                                            break;
                                        case 9:
                                            // 文化程度
                                            pzPersonWithBLOBs.setpEducation((sysCodeMapper.getByName("DEGREE",cell.getStringCellValue().trim())).getCodeNo());
                                            break;
                                        case 10:
                                            // 婚姻状况
                                            if(cell.getStringCellValue().equals("未婚")){
                                                pzPersonWithBLOBs.setpMaritalStatus("01");
                                            }else if(cell.getStringCellValue().equals("已婚")){
                                                pzPersonWithBLOBs.setpMaritalStatus("02");
                                            }
                                            break;
                                        case 11:
                                            //宗教信仰
                                            pzPersonWithBLOBs.setpReligion(cell.getStringCellValue());
                                            break;
                                        case 12:
                                            //职业
                                            pzPersonWithBLOBs.setpOccupation(cell.getStringCellValue());
                                            break;
                                        case 13:
                                            //工作单位
                                            pzPersonWithBLOBs.setpWorkUnit(cell.getStringCellValue());
                                            break;
                                        case 14:
                                            //户籍地址
                                            pzPersonWithBLOBs.setpDomicile(cell.getStringCellValue());
                                            break;
                                        case 15:
                                            //籍贯
                                            pzPersonWithBLOBs.setpOrigin(cell.getStringCellValue());
                                            break;
                                        case 16:
                                            //户籍地详址
                                            pzPersonWithBLOBs.setpDetailedDomicile(cell.getStringCellValue());
                                            break;
                                        case 17:
                                            //名下机动车辆
                                            if(cell.getStringCellValue().equals("有")){
                                                pzPersonWithBLOBs.setpVehicles("0");
                                            }else if(cell.getStringCellValue().equals("无")){
                                                pzPersonWithBLOBs.setpVehicles("1");
                                            }
                                            break;
                                        case 18:
                                            //备注
                                            pzPersonWithBLOBs.setpRemarks(cell.getStringCellValue());
                                            break;
                                        case 19:
                                            //有无固定住所
                                            if(cell.getStringCellValue().equals("无")){
                                                pzPersonWithBLOBs.setpIsHouse("0");
                                            }else if(cell.getStringCellValue().equals("有")){
                                                pzPersonWithBLOBs.setpIsHouse("1");
                                            }
                                            break;
                                        case 20:
                                            //现居地址
                                            pzPersonWithBLOBs.setpAddress(cell.getStringCellValue());
                                            break;
                                        case 21:
                                            //实口类型
                                            if(cell.getStringCellValue().equals("流动人口")){
                                                pzPersonWithBLOBs.setFlag1("2");
                                            }else if(cell.getStringCellValue().equals("户籍人口")){
                                                pzPersonWithBLOBs.setFlag1("1");
                                            }
                                            break;
                                        case 22:
                                            //车牌号
                                            cell.setCellType(CellType.STRING);
                                            pzPersonWithBLOBs.setStr1(cell.getStringCellValue());
                                            break;
                                        case 23:
                                            // 接受方式
                                            pzCorrectionWithBLOBs.setAcceptWay((sysCodeMapper.getByName("ACCEPT_WAY",cell.getStringCellValue().trim())).getCodeNo());
                                            break;
                                        case 24:
                                            // 关注程度
                                            pzCorrectionWithBLOBs.setAttentionLevel((sysCodeMapper.getByName("RENT_CONCERN",cell.getStringCellValue().trim())).getCodeNo());
                                            break;
                                        case 25:
                                            // 原羁押场所
                                            pzCorrectionWithBLOBs.setDetentionOriginalPlace(cell.getStringCellValue());
                                            break;
                                        case 26:
                                            // 犯罪类型
                                            pzCorrectionWithBLOBs.setCrimeTypes((sysCodeMapper.getByName("P_CRIME_TYPE",cell.getStringCellValue().trim())).getCodeNo());
                                            break;
                                        case 27:
                                            // 具体罪名
                                            pzCorrectionWithBLOBs.setSpecificCharges(cell.getStringCellValue());
                                            break;
                                        case 28:
                                            // 是否有四史
                                            pzCorrectionWithBLOBs.setFourHistoryFlag("否".equals(cell.getStringCellValue())?"0":"1");

                                            break;
                                        case 29:
                                            // 是否有三涉
                                            pzCorrectionWithBLOBs.setThreeStakeholdersFlag("否".equals(cell.getStringCellValue())?"0":"1");
                                            break;
                                        case 30:
                                            // 是否累惯犯
                                            pzCorrectionWithBLOBs.setRepeatOffendersFlag("否".equals(cell.getStringCellValue())?"0":"1");
                                            break;
                                        case 31:
                                            //服刑类别
                                            pzCorrectionWithBLOBs.setSentenceCategory((sysCodeMapper.getByName("SENTENCE_CATEGORY",cell.getStringCellValue().trim())).getCodeNo());
                                            break;
                                        case 32:
                                            //原判刑期
                                            pzCorrectionWithBLOBs.setOriginalSentence(cell.getStringCellValue());
                                            break;
                                        case 33:
                                            //原判刑期开始时间
                                            SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
                                            Date date1=sdf1.parse(cell.getStringCellValue());
                                            pzCorrectionWithBLOBs.setOriginalSentenceBeginTime(date1);
                                            break;
                                        case 34:
                                            //原判刑期结束时间
                                            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
                                            Date date2=sdf.parse(cell.getStringCellValue());
                                            pzCorrectionWithBLOBs.setOriginalSentenceEndTime(date2);
                                            break;
                                        case 35:
                                            //服刑开始时间
                                            SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");
                                            Date date3=sdf2.parse(cell.getStringCellValue());
                                            pzCorrectionWithBLOBs.setSentenceBeginTime(date3);
                                            break;
                                        case 36:
                                            //服刑结束时间
                                            SimpleDateFormat sdf3=new SimpleDateFormat("yyyy-MM-dd");
                                            Date date4=sdf3.parse(cell.getStringCellValue());
                                            pzCorrectionWithBLOBs.setSentenceEndTime(date4);
                                            break;
                                        case 37:
                                            //近况描述
                                            pzCorrectionWithBLOBs.setRecentDescription(cell.getStringCellValue());
                                            break;
                                        default:
                                            toJson.setFlag(0);
                                            toJson.setMsg("err");
                                            break;
                                    }
                                }

                            }
                            List<String> nullArray=new ArrayList();
                            if(pzPersonWithBLOBs.getpGrid()==null){
                                nullArray.add("特殊网格");
                            }
                            if(pzPersonWithBLOBs.getpName()==null){
                                nullArray.add("姓名");
                            }
                            if(pzPersonWithBLOBs.getpSex()==null){
                                nullArray.add("性别");
                            }
                            if(pzPersonWithBLOBs.getpCradId()==null){
                                nullArray.add("身份证号");
                            }
                            if(pzPersonWithBLOBs.getFlag1()==null){
                                nullArray.add("实口类型");
                            }
                            if(pzPersonWithBLOBs.getpOrigin()==null){
                                nullArray.add("籍贯");
                            }
                            if(pzPersonWithBLOBs.getpIsHouse()==null){
                                nullArray.add("有无固定住所");
                            }
                            if(pzPersonWithBLOBs.getpAddress()==null){
                                nullArray.add("现居地址");
                            }
                            if(pzPersonWithBLOBs.getpMaritalStatus()==null){
                                nullArray.add("婚姻状况");
                            }
                            if(pzPersonWithBLOBs.getpDomicile()==null){
                                nullArray.add("户籍地址");
                            }
                            if(pzPersonWithBLOBs.getpDetailedDomicile()==null){
                                nullArray.add("户籍地详情");
                            }
                            if(pzPersonWithBLOBs.getpVehicles()==null){
                                nullArray.add("名下机动车辆");
                            }
                            if(pzCorrectionWithBLOBs.getAcceptWay()==null){
                                nullArray.add("接受方式");
                            }
                            if(pzCorrectionWithBLOBs.getSpecificCharges()==null){
                                nullArray.add("具体罪名");
                            }
                            if(pzCorrectionWithBLOBs.getSentenceCategory()==null){
                                nullArray.add("服刑类别");
                            }
                            if(nullArray.size()>0){
                                toJson.setObject(nullArray);
                                toJson.setMsg("必填字段不能为空，请重新导入");
                            }else {
                                //判断用户是否为空，不为空判断用户是否存在
                                if(!StringUtils.checkNull(pzPersonWithBLOBs.getpName())&&!StringUtils.checkNull(pzPersonWithBLOBs.getpCradId())){
                                    Map<String, Object> map = new HashMap<String, Object>();
                                    map.put("pCradId", pzPersonWithBLOBs.getpCradId());
                                    map.put("pName", pzPersonWithBLOBs.getpName());
                                    PzPersonWithBLOBs pzPersons=pzPersonMapper.selectPersonCountByNameCrad(map);
                                    if(pzPersons.getCount()>0){
                                        pzPersonWithBLOBs.setpId(pzPersons.getpId());
                                        pzCorrectionWithBLOBs.setUserId(String.valueOf(pzPersons.getpId()));
                                        pzPersonWithBLOBs.setFlag2("0");
                                        if(!pzPersons.getSpecialStr().contains("2,")){
                                            String str = "2," + pzPersons.getSpecialStr();
                                            pzPersonWithBLOBs.setSpecialStr(str);
                                        }
                                        pzPersonMapper.updateByPrimaryKeySelective(pzPersonWithBLOBs);
                                    }else {
                                        //创建用户和创建时间
                                        pzPersonWithBLOBs.setCreateUser(users.getUserId());
                                        pzPersonWithBLOBs.setCreateTime(DateFormat.getCurrentTime());
                                        pzPersonWithBLOBs.setFlag2("0");
                                        pzPersonWithBLOBs.setSpecialStr("2,");
                                        pzPersonMapper.insertSelective(pzPersonWithBLOBs);
                                        pzCorrectionWithBLOBs.setUserId(String.valueOf(pzPersonWithBLOBs.getpId()));
                                    }
                                }
                                //将数据放入数据库
                                //用户表与表关联用户userid
                                pzCorrectionWithBLOBs.setUserId(String.valueOf(pzPersonWithBLOBs.getpId()));
                                //判断关联用户userid是否为空,为空新增,不为空修改
                                if(!StringUtils.checkNull(pzCorrectionWithBLOBs.getUserId())){
                                    //如果不为空，查询是否有信息，有则更新，否则新增
                                    Map<String, Object> map = new HashMap<String, Object>();
                                    map.put("userId", pzCorrectionWithBLOBs.getUserId());
                                    PzCorrection pzCorr=pzCorrectionMapper.selectByUserId(map);
                                    if(pzCorr.getCou()>0){
                                        pzCorrectionWithBLOBs.setCorrectionId(pzCorr.getCorrectionId());
                                        count += pzCorrectionMapper.updateByPrimaryKeySelective(pzCorrectionWithBLOBs);
                                    }else {
                                        //创建用户和创建时间
                                        pzCorrectionWithBLOBs.setCreateUser(users.getUserId());
                                        pzCorrectionWithBLOBs.setCreateTime(DateFormat.getCurrentTime());
                                        count += pzCorrectionMapper.insertSelective(pzCorrectionWithBLOBs);
                                    }
                                }
                            }
                        }
                    }
                    if(count>0) {
                        successCount = successCount + count;
                    }
                    dest.delete();
                    if(successCount>0){
                        toJson.setTotleNum(successCount);
                        toJson.setMsg("ok");
                        toJson.setFlag(0);
                        return  toJson;
                    }
                }
            }
        } catch (Exception e) {
            //读取配置文件,获取文件要存储的路径
            StringBuffer path = this.getPath();
            String fileName = file.getOriginalFilename();
            if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                String extName = fileName
                        .substring(fileName.lastIndexOf(".") + 1);// 文件后缀
                String newFileName = uuid + extName;//组合成新的文件名
                File dest = new File(path.toString(), newFileName);
                dest.delete();
            }
            e.getMessage();
            e.printStackTrace();
        }

        return toJson;
    }

    //判读当前系统,读取配置文件,返回路径
    public StringBuffer getPath(){
        ResourceBundle rb = ResourceBundle.getBundle("upload");
        String osName = System.getProperty("os.name");
        StringBuffer path = new StringBuffer();
        if (osName.toLowerCase().startsWith("win")) {
            path = path.append(rb.getString("upload.win"));
        } else {
            path = path.append(rb.getString("upload.linux"));
        }
        return path;
    }
}
